<template>
  <div class="ui-page page__has-bottom page-order-confirm">
    <div class="page-container">
      <div class="order-confirm--container">
        <!-- 支付方式 -->
        <div class="confirm-pattern">
          <uiCellGroup v-model="payment" title-width="500rpx">
            <!-- 如果不是专属课程，且不存在优惠价 那么就可以微信支付 -->
            <div
              class="confirm-panel"
              v-if="lesson.targetType != 3 || lesson.isCheap !== 'Y'"
              style="margin-top:0"
            >
              <div class="panel-header">支付方式</div>
              <div class="panel-body" style="padding-bottom:0">
                <uiCell>
                  <template v-slot:title>
                    <div class="confirm-radion--label">
                      <image
                        class="confirm-radion--weixin-image"
                        src="/static/images/detail/weixin.jpg"
                        alt
                        srcset
                      />
                      <span>微信支付</span>
                    </div>
                  </template>
                  <template v-slot:value>
                    <uiRadio
                      class="confirm-radio confirm-radion--weixin"
                      name="1"
                      label-position="left"
                      :value="payment === '1'"
                      @change="handleChangePayment($event , '1')"
                    ></uiRadio>
                  </template>
                </uiCell>
                <uiCell>
                  <template v-slot:title>
                    <div class="confirm-radion--label">
                      <span>激活码兑换</span>
                      <span class="confirm-radion--icon duihuan">兑换>></span>
                    </div>
                  </template>
                  <template v-slot:value>
                    <uiRadio
                      class="confirm-radio confirm-radion--weixin"
                      name="1"
                      label-position="left"
                      :value="payment === '2'"
                      @change="handleChangePayment($event , '2')"
                    ></uiRadio>
                  </template>
                </uiCell>
              </div>
              <div class="panel-body"></div>
            </div>
          </uiCellGroup>
          <div class="confirm-pattern--tips">每笔订单只能使用一次激活码</div>
        </div>
      </div>
    </div>
    <div class="page-bottom page-view-submit-bar">
      <!-- // 监听支付方式，使得submitbar显示不同 -->
      <!-- VIP购买 -->
      <div class="submit-bar--container" v-if="payment === '2'">
        <span class="submit-bar--info">
          <span>购买VIP</span>
        </span>
        <span class="submit-bar--submit" @click="handleClickGotoVIP">立即购买</span>
      </div>
      <div class="submit-bar--container" v-else-if="payment === '3'">
        <span class="submit-bar--info">
          <span>激活码兑换</span>
        </span>
        <span class="submit-bar--submit" @click="handleClickGotoActivationCode">立即激活</span>
      </div>
      <div class="submit-bar--container" v-else>
        <span class="submit-bar--info">
          <!-- 如果是优惠价 -->
          <span v-if="lesson.isVip === 'Y' && user.isVip === 'Y'">
            VIP优惠价
            <span
              class="submit-bar--info-color"
            >{{lesson.lessonCheapPrice | currency_format('￥')}}</span>
          </span>
          <span v-else>
            实付
            <span class="submit-bar--info-color">{{lesson.lessonPrice | currency_format('￥')}}</span>
          </span>
        </span>
        <span class="submit-bar--submit" @click="handleClickWeixinPay">立即购买</span>
      </div>
    </div>
  </div>
</template>

<script>
import uiRadio from "@/components/base/radio/index";
import uiCellGroup from "@/components/base/cell-group/index";
import uiCell from "@/components/base/cell/index";

import { payLessonInfo, addOrderAPI, wechatPayAPI } from "api/order/order.js";
import { wxPay } from "@/utils/wx.js";
export default {
  name: "orderComfirmPage",
  components: {
    uiRadio,
    uiCellGroup,
    uiCell
  },
  data() {
    return {
      lessonId: "",
      // 支付方式
      payment: "1",
      // 当前用户的信息
      user: {
        isVip: "N"
      },
      lesson: {
        lessonPic: "",
        lessonName: "",
        lessonPrice: "",
        isCheap: "",
        // 课程是否是VIP课程
        isVip: "N",
        // targetType，1是课程，2是会员课程，3是专属
        targetType: 1,
        // 优惠价
        lessonCheapPrice: ""
      }
    };
  },
  onLoad(e) {
    // this.lessonId = e.id;
    this.lessonId = 353;
    this.loadOrderBasicInfo();
  },
  created() {},
  watch: {},
  methods: {
    handleChangePayment(e, payVal) {
      debugger;

      this.payment = payVal;
    },
    /**
     * 加载当前课程的订单信息
     */
    loadOrderBasicInfo() {
      var params = {
        targetId: this.lessonId,
        targetType: 1
      };
      var self = this;
      payLessonInfo(params).then(({ respCode, respMsg, result }) => {
        if (respCode !== "0") {
          this.$toast.fail(respMsg);
        }
        if (result) {
          // 课程的信息
          this.lesson.lessonPic = result.lessonPowerInfo.lesson.lessonPic;
          this.lesson.lessonName = result.lessonPowerInfo.lesson.lessonName;
          // 课程的正常价格
          this.lesson.lessonPrice =
            result.lessonPowerInfo.lesson.lessonPrice || 0;
          // targetType，1是课程，2是会员，3是专属
          this.lesson.targetType = result.lessonPowerInfo.targetType;
          // lessonPowerInfo.targetType === 2代表这个课程是VIP课程
          this.lesson.isVip =
            result.lessonPowerInfo.targetType === 2 ? "Y" : "N";
          // 当前用户是否是VIP，修改返回数据中 N === null 改为 是(Y) 否(N)
          this.lesson.isCheap = result.lessonPowerInfo.isCheap ? "Y" : "N";
          // 课程的优惠价格
          this.lesson.lessonCheapPrice =
            result.lessonPowerInfo.lesson.lessonCheapPrice || 0;
          // 当前用户是否是VIP，修改返回数据中 N === null 改为 是(Y) 否(N)
          this.user.isVip = result.lessonPowerInfo.isVip === 1 ? "Y" : "N";
        }
      });
    },
    /**
     * 购买VIP
     * 跳转到VIP购买页面
     */
    handleClickGotoVIP() {
      this.$router.push({
        path: `/my/subscriber`,
        query: {
          sid: this.$route.query.sid
        }
      });
    },
    /**
     * 激活码兑换
     * 跳转到激活码兑换页面
     */
    handleClickGotoActivationCode() {
      // 第一步 生成订单
      var params = {
        orderType: 1,
        productId: this.lessonId,
        productNum: 1
      };
      addOrderAPI(params).then(({ respCode, respMsg, result }) => {
        if (respCode !== "0") {
          // 加载失败
          this.$toast.fail(respMsg);
          return;
        }
        if (result) {
          this.$router.push({
            path: `/order/activation-code/${result}`,
            query: {
              sid: this.$route.query.sid,
              redirect: `/lession/detail?id=${this.lessonId}`,
              type: 2
            }
          });
        }
      });
    },
    /**
     * 微信支付购买
     * 进行微信支付操作
     */
    handleClickWeixinPay() {
      let _this = this;
      const beforeCreateOrder = () => {
        return new Promise((resolve, reject) => {
          var params = {
            amount: this.lessonPrice,
            orderType: 1,
            productId: this.lessonId,
            productNum: 1
          };
          var self = this;
          addOrderAPI(params).then(({ respCode, respMsg, result }) => {
            if (respCode !== "0") {
              // 加载失败
              this.$toast.fail(respMsg);
              reject({
                respMsg: respMsg
              });
              return;
            }
            if (result) {
              resolve({
                orderNo: result
              });
            }
          });
        });
      };

      const readyPay = orderNo => {
        return new Promise((resolve, reject) => {
          var params = {
            out_trade_no: orderNo
          };
          var self = this;
          wechatPayAPI(params).then(({ respCode, respMsg, result }) => {
            if (respCode !== "0") {
              // 加载失败
              this.$toast.fail(respMsg);
              reject({
                respMsg: respMsg
              });
              return;
            }
            if (result) {
              resolve({
                ...result
              });
            }
          });
        });
      };

      beforeCreateOrder().then(({ orderNo }) => {
        readyPay(orderNo).then(
          ({ appid, timeStamp, nonceStr, packAge, signType, paySign }) => {
            wxPay(appid, timeStamp, nonceStr, packAge, signType, paySign)
              .then(() => {
                _this.$url.navigateTo({
                  url: "/page/buy/pay-succes/index",
                  query: {
                    orderNo: orderNo
                  }
                });
              })
              .catch(({ respCode, respMsg }) => {
                this.$dialog.alert({
                  title: "取消支付",
                  message: respMsg
                });
              });
          }
        );
      });
    }
  }
};
</script>

<style lang="scss" src="./index.scss"></style>
